package com.bcdat.sso_user_management.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bcdat.sso_user_management.model.CasUser;
import com.bcdat.sso_user_management.model.User;
import com.bcdat.sso_user_management.service.SimpleHashService;
import com.bcdat.sso_user_management.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhaolele
 * @date 2019-09-25 11:35
 */
@Slf4j
@RestController
@RequestMapping("cas/user")
public class CasUserController {
    @Autowired
    UserService userService;

    @Autowired
    SimpleHashService hashService;

    @PostMapping("login")
    @ApiOperation(value = "CAS服务器获取用户信息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "authorization", paramType = "header")
    })

    public ResponseEntity<CasUser> casLogin(@RequestHeader HttpHeaders httpHeaders) {

        log.info("cas rest api login");
        String authorB64 = httpHeaders.getFirst("authorization").split(" ")[1];
        log.debug("authorization::::", authorB64);
        String authorization = new String(Base64Utils.decodeFromString(authorB64));
        String[] split = authorization.split(":");

        User existUser = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUsername, split[0]));
        if (existUser == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        String hashPassword = hashService.simpleHash(existUser.getUsername(), split[1]);
        if (!existUser.getPassword().equals(hashPassword)) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        if (existUser.getDisabled()) {
            return new ResponseEntity<>(HttpStatus.FORBIDDEN);
        }
        if (existUser.getExpired()) {
            return new ResponseEntity<>(HttpStatus.LOCKED);
        }
        CasUser casUser = new CasUser();
        casUser.setId(existUser.getUsername());
        return new ResponseEntity<>(casUser, HttpStatus.OK);
    }
}
